package avicit.bdp.dcs.semistructure.suite;

import avicit.bdp.dcs.Constant;
import avicit.bdp.dcs.semistructure.dto.TemplateDTO;
import avicit.bdp.dcs.semistructure.utils.Constants;
import avicit.platform6.core.rest.msg.ResponseMsg;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class TemplateSuiteTest {
    public static final String USER_NAME = "avicit2015";
    public static final String PASS_WORD = "avicit2015";
    public static final String HTTP_OK = "200";
    public static final String URL_PREFIX = Constant.HOSTPORT + "/api/bdp/dcs/template/TemplateRest/";
    private String fileName;

    @Before
    public void setUp() throws Exception {
        // 创建模板文件
        fileName = "template_" + System.currentTimeMillis() + ".csv";
        File file = new File(System.getProperty("user.dir") + "/" + fileName);
        if(!file.exists()){
            file.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(file.getName(), true);
        fileWriter.write("name,age,work");
        fileWriter.close();
        System.out.println("文件创建成功！");
    }

    @After
    public void tearDown() throws Exception {
        // 删除模板文件
        File file = new File(System.getProperty("user.dir") + "/" + fileName);
        file.delete();
        System.out.println("删除文件成功！");
    }
    @Test
    public void testTemplate() {
        // 上传模板文件
        RestTemplate restTemplate  = new RestTemplateBuilder().basicAuthentication(USER_NAME, PASS_WORD).build();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        FileSystemResource fileSystemResource = new FileSystemResource(System.getProperty("user.dir")+"/"+fileName);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        form.add("filename",fileName);
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        ResponseMsg uploadResult = restTemplate.postForObject(URL_PREFIX + "upload", files, ResponseMsg.class);
        assertEquals(HTTP_OK, uploadResult.getRetCode());
        List<String> columnList = (List<String>) uploadResult.getResponseBody();
        // 获取模板列表
        ResponseEntity<ResponseMsg> startListResult = restTemplate.getForEntity(URL_PREFIX + "getTemplateListByName",
                ResponseMsg.class);
        ResponseMsg body = startListResult.getBody();
        List<TemplateDTO> list = (List<TemplateDTO>) body.getResponseBody();
        int startSize = list.size();
        System.out.println("模板个数为：" + startSize);
        assertEquals(HTTP_OK, startListResult.getBody().getRetCode());
        // 保存模板数据
        ResponseEntity<ResponseMsg> result = restTemplate.postForEntity(URL_PREFIX + "createTemplate",
                buildSaveTemplateParas(
                        "test",fileName, columnList), ResponseMsg.class);
        assertEquals("200", result.getBody().getRetCode());
        // 获取模板列表
        ResponseEntity<ResponseMsg> endListResult = restTemplate.getForEntity(URL_PREFIX + "getTemplateListByName",
                ResponseMsg.class);
        ResponseMsg endBody = endListResult.getBody();
        List<Map> endList = (List<Map>) endBody.getResponseBody();
        int endSize = endList.size();
        System.out.println("模板个数为：" + startSize);
        assertEquals(HTTP_OK, endListResult.getBody().getRetCode());
        assertEquals(1, endSize - startSize);
        // 更新模板数据
        endList.removeAll(list);
        assertEquals(1, endList.size());
        String templateId = "";
        for (Map templateDto: endList) {
            templateId = (String) templateDto.get("id");
            TemplateDTO templateDTO = new TemplateDTO();
            templateDTO.setId(templateId);
            templateDTO.setColumnRule((String) templateDto.get("columnRule"));
            templateDTO.setFileSeparator((String) templateDto.get("fileSeparator"));
            templateDTO.setFileType((Integer) templateDto.get("fileType"));
            templateDTO.setTemplateName((String) templateDto.get("templateName"));
            ResponseEntity<ResponseMsg> updateTemplateResult = restTemplate.postForEntity(URL_PREFIX +
                            "updateTemplate", buildUpdateTemplateParas(templateDTO), ResponseMsg.class);
            assertEquals("200", updateTemplateResult.getBody().getRetCode());
        }
        // 下载模板
        HttpHeaders downloadHeaders = new HttpHeaders();
        List mediaTypeList = new ArrayList<>();
        mediaTypeList.add(MediaType.valueOf("application/json"));
        downloadHeaders.setAccept(mediaTypeList);
        ResponseEntity<byte[]> response = restTemplate.exchange(URL_PREFIX + "downloadTemplate?templateId" +
                        "=" + templateId, HttpMethod.GET, new HttpEntity<byte[]>(downloadHeaders),
                byte[].class);
        assertEquals(HTTP_OK, response.getStatusCode().value()+"");
        System.out.println(new String(response.getBody()));
        assertEquals("name,age,work", new String(response.getBody()));
        // 删除模板
        ResponseEntity<ResponseMsg> deleteResult = restTemplate.exchange(URL_PREFIX + "deleteTemplateByIds",
                HttpMethod.DELETE, buildDeleteTemplateParas(templateId), ResponseMsg.class);
        assertEquals(HTTP_OK, deleteResult.getBody().getRetCode());
    }

    private HttpEntity<String> buildDeleteTemplateParas(String templateId) {
        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setId(templateId);
        String param = JSONObject.toJSONString(templateDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    private Object buildUpdateTemplateParas(TemplateDTO templateDto) {
        templateDto.setRemark("000000000000");
        String param = JSONObject.toJSONString(templateDto);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    private HttpEntity<String> buildSaveTemplateParas(String remark, String templateName, List<String> columnList) {
        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setRemark(remark);
        JSONArray jsonArray = new JSONArray();
        for (String column: columnList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", column);
            jsonObject.put("type", "TEXT");
            jsonArray.add(jsonArray);
        }
//        templateDTO.setColumnRule("[{\"name\":\"name\",\"type\":\"TEXT\"},{\"name\":\"age\",\"type\":\"TEXT\"},{\"name\":\"work\",\"type\":\"TEXT\"}]");
        templateDTO.setColumnRule(jsonArray.toJSONString());
        templateDTO.setTemplateName(templateName);
        templateDTO.setFileType(2);
        templateDTO.setFileSeparator(",");

        String param = JSONObject.toJSONString(templateDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }
}
